import requests
import json
import re


def pve_login(domain, username, password):
# 获取cookies
# ticket:res['data']['ticket']  任何请求都需要用到ticket
# CSRF防止令牌:res['data']['CSRFPreventionToken']  写请求需要用到CSRF 
    login_url = domain + "api2/json/access/ticket"
    login_data = {"username":username, "password":password}
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0"}
    res = requests.post(login_url, data=login_data, headers=headers).text
    res = json.loads(res)
    return res['data']['ticket'], res['data']['CSRFPreventionToken']

def pve_source(ticket, CSRF, source_type, domain):
# 获取资源信息
    get_source_url = domain + "api2/json/cluster/resources"
    cookies = {'PVEAuthCookie':ticket}
    headers = {'CSRFPreventionToken':CSRF}
    params = {'type':source_type}
    sources = requests.get(get_source_url, cookies=cookies, headers=headers, params=params).text
    sources = json.loads(sources)
    return sources

def pve_node_ip(ticket, CSRF, node, domain):
    cookies = {'PVEAuthCookie':ticket}
    headers = {'CSRFPreventionToken':CSRF}
    get_ip_url = domain + "api2/json/nodes/" + str(node) + "/hosts"
    ret = requests.get(get_ip_url, cookies=cookies, headers=headers)
    # print(ret.text)
    ip = json.loads(ret.text)['data']['data']
    ip = re.search(r"172\.18\.\d{1,3}\.\d{1,3}", ip, re.I|re.M).group()
    return ip

def pve_physical_ip(hostname):
    # domain = "https://pve.smyjf.cn/"
    # username = "root@pam"
    # password = "eG4vue!paA"

    domain1 = "https://prdpve.smyoa.com/"
    username1 = "root@pam"
    password1 = "Smy12345"

    domain2 = "https://pve01.smyoa.com/"
    username2 = "root@pam"
    password2 = "pre_siy_pve@20200602!"
    sources_dict = {}

    ticket, CSRF = pve_login(domain1, username1, password1)
    sources = pve_source(ticket,CSRF,'vm', domain1)["data"]
    for i in sources:
        sources_dict[i['name']] = pve_node_ip(ticket,CSRF,i['node'],domain1)

    ticket, CSRF = pve_login(domain2, username2, password2)
    sources = pve_source(ticket,CSRF,'vm', domain2)["data"]
    for i in sources:
        sources_dict[i['name']] = pve_node_ip(ticket,CSRF,i['node'],domain2)
    
    # print(sources_dict)
    return sources_dict[hostname]

a = pve_physical_ip("sz.wg1.pve.prd.bda-oms-new.host01")
print(a)
